package com.dingpeikeji.quickdeer.mobile.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.modules.count.entity.CountInfo;
import com.dingpeikeji.quickdeer.core.modules.count.service.TCountService;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.dao.UserDao;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Area;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Role;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.SysAds;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.core.modules.sys.service.SysAdsService;
import com.dingpeikeji.quickdeer.core.modules.sys.service.SystemService;
import com.dingpeikeji.quickdeer.mobile.web.MobileJsonController;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.sms.entity.Sms;
import com.dingpeikeji.quickdeer.modules.sms.service.CkeckTelephoneService;
import com.dingpeikeji.quickdeer.modules.sms.service.SmsApi;
import com.dingpeikeji.quickdeer.modules.utils.ValidateCodeTool;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.dingpeikeji.quickdeer.utils.JedisClient;
import com.dingpeikeji.quickdeer.utils.JsonUtils;
import com.dingpeikeji.quickdeer.utils.StringUtil;
import com.dingpeikeji.quickdeer.utils.UUIDUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Service
@Transactional(readOnly = true)
public class MobileUserService {
	public static final String FRONT_USER = "frontUser";
	// 验证码用途
	public static final String[] validateCodeTypes = new String[]{"validateCodeFromPhoneForRegister","validateCodeFromPhoneForDriver", "validateCodeFromPhoneForPassword"};
	@Autowired
	private FrontUserService userService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private TSitedtlService sitedtlService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private JedisClient jedisClient;
	@Autowired
	private CkeckTelephoneService ckeckTelephoneService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private SysAdsService sysAdsService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private TCountService tCountService;
	
	public BackResult login(String username, String password) {
		User user = new User();
		user.setLoginName(username);
		List<User> userList = userService.findList(user);
		if(userList != null && !userList.isEmpty()) { // 存在用户
			user = userList.get(0);
			user.setOffice(officeService.get(user.getOffice()));
			if(user.getLoginFlag().equals("1")){
				Office office = officeService.get(user.getOffice()); // 用户所属部门
				user.setOffice(office);
				// 比对密码
				if(SystemService.validatePassword(password, user.getPassword())) {
					user = userList.get(0);
					user.setFlatType(user.getOffice().getFlatType());
					//生成token
					String token = UUIDUtils.getId();
					//清空密码(不需要存储)
					user.setPassword(null);
					user.setUid(user.getId());//手机端返回id关键字,uid替代
					//把用户信息存到jedis,key就是token,value就是用户信息
					jedisClient.set(MobileJsonController.FRONT_USER+" : "+token, JsonUtils.objectToJson(user));
					//设置key过期时间,30天
					//jedisClient.expire(MobileJsonController.FRONT_USER+" : "+token, 30* 24 * 60 * 60);
					return BackResult.ok(token);
				}
				return BackResult.build("500", "用户名或密码不正确");
			} else {
				return BackResult.build("401", "该账号已禁用");
			}
		}else{
			return BackResult.build("400", "用户名不存在");
		}
	}

	public BackResult getUserByToken(String token) {
		String json = jedisClient.get(MobileJsonController.FRONT_USER+" : "+token);
		if (StringUtils.isBlank(json)) {
			return BackResult.build("400", "用户登录已经过期");
		}
		//把json转换成User对象
		User user = JsonUtils.jsonToPojo(json, User.class);
		if (user.getUserimage()==null) {
			user.setUserimage("");//用户头像,如果是null,json获取不到数据
		}
		return BackResult.ok(user);
	}
	public BackResult getBannerImage() {
		List<SysAds> sysAds = sysAdsService.getBannerImage();
		return BackResult.ok(sysAds);
	}
	public BackResult logoutByToken(String token) {
		String json = jedisClient.get(MobileJsonController.FRONT_USER+" : "+token);
		if (StringUtils.isBlank(json)) {
			return BackResult.build("400", "未查询到用户信息");
		}
		//删除token
		try {
			Long del = jedisClient.del(MobileJsonController.FRONT_USER+" : "+token);
			if (del==0) {
				return BackResult.build("500", "token参数不正确");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return BackResult.build("500", "未知错误");
		}
		return BackResult.ok();
	}

	public BackResult sendMes(String phone, Integer type,HttpServletRequest request) {
		if(ValidateTool.isEmptyOrNull(phone) || !ValidateTool.isMobile(phone)) {
			return BackResult.build("500", "手机号非法,请重新输入");
		}
		if(type == null || type<0 || type > 2){
			return BackResult.build("500", "发送短信出错,请联系网站管理员");
		}
		//Map<String,Object> map =new HashMap<String, Object>();
		// 开始发送短信
		String code = ValidateCodeTool.genCode();
		try {
			Sms sendSms = new Sms();
			sendSms.setMobile(phone);
			sendSms.setContent("本次验证码为："+code+"，有效时间为2分钟");
			if (SmsApi.sendSms(sendSms) == false)
			return BackResult.build("500", "发送失败");
		} catch (Exception e) {
			return BackResult.build("500", "系统异常");
		}
		/*map = Maps.newHashMap();
		map.put("time", new Date().getTime());
		map.put("code", code);
		request.getSession().setAttribute("registercode", map);*/
		jedisClient.set("registercode: "+phone, code);
		//重置token的过期时间
		jedisClient.expire("registercode: "+phone, 60*2);
		//把json转换成User对象
		//JSONObject json = JsonUtils.mapToJson(map);
		return BackResult.ok();
	}
	
	public BackResult checkData(String data, int type) {
		// 1.判断手机号码是否可用
		if (type == 1) {
			if(ValidateTool.isEmptyOrNull(data) || !ValidateTool.isMobile(data)) {
				return BackResult.build("500", "手机号非法");
			}else{
				User user = ckeckTelephoneService.getUserByTelephone(data);
				if (user == null) {  //手机号未注册,可以使用
					return BackResult.ok(true);
				} else {
					return BackResult.build("400", "手机号码已被注册");
				}
			}
			// 2判断密码格式
		} else if (type == 2) {
			if(ValidateTool.isEmptyOrNull(data) || !ValidateTool.isPassword(data)) {
				return BackResult.build("500", "6-16位数字和字母的组合");
			}else{
				return BackResult.ok(true);
			}
			// 3判断邮箱是否可以使用
		} else if (type == 3) {
			if(ValidateTool.isEmptyOrNull(data) || !ValidateTool.isEmail(data)) {
				return BackResult.build("500", "邮箱格式错误");
			}else{
				return BackResult.ok(true);
			}
		} else {
			return BackResult.build("400", "参数中包含非法数据");
		}
	}
	public BackResult forgetPwd(String mobile, String password1, String password2,
			String validateCode, HttpServletRequest request) {
		List<String> messages = Lists.newArrayList(); // 消息
		String mobileFromRedisCode = jedisClient.get("registercode: "+mobile);
		if (StringUtil.isEmpty(mobileFromRedisCode)) {
			return BackResult.build("400","短信验证码超时");
		}
		if (!mobileFromRedisCode.equals(validateCode)) {
			return BackResult.build("400","短信验证码错误");
		}
		if(messages.isEmpty()) {
			if (!password1.equals(password2) || StringUtils.isEmpty(password1) || StringUtils.isEmpty(password2)) {
				return BackResult.build("400","密码不一致");
			}
			if(ValidateTool.isEmptyOrNull(mobile) || !ValidateTool.isMobile(mobile)) {
				return BackResult.build("500", "手机号非法");
			}
			String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
			if (!password1.matches(regex)||!password2.matches(regex)) {
				return BackResult.build("400","密码为6-16位数字和字母的组合");
			}
			User user = new User();
			user.setLoginName(mobile);
			List<User> userList = systemService.findList(user);
			if(userList!=null && !userList.isEmpty()){
				user = userList.get(0);
				systemService.updatePasswordById(user.getId(), user.getLoginName(), password1);
				return BackResult.build("200", "密码修改成功,请重新登录");
			} else {
				return BackResult.build("400", "手机号未注册");
			}
		}else {
			return BackResult.build("400", messages.get(0));
		}
	}

	public BackResult modifyPwd(String token,String oldPassword,String newPassword,String repeatPassword){
		String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(repeatPassword)){
			if(!newPassword.equals(repeatPassword)){
				return BackResult.build("400","两次密码输入不一致");
			}else if(!newPassword.matches(regex)){
				return BackResult.build("400","修改密码失败，密码格式为6-16位数字和字母的组合");
			} else  {
				String json = jedisClient.get(MobileJsonController.FRONT_USER+" : "+token);
				if (StringUtils.isEmpty(json)) {//没有查询到用户信息
					return BackResult.build("400", "查询用户信息失败");
				}
				User user = JsonUtils.jsonToPojo(json, User.class);
				user = userService.get(user.getId());//目的:获取密码,redis没有密码
				if (SystemService.validatePassword(oldPassword, user.getPassword())){
					systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
					user.setPassword(null);
					jedisClient.set(MobileJsonController.FRONT_USER+" : "+token, JsonUtils.objectToJson(user));
					//jedisClient.expire(MobileJsonController.FRONT_USER+" : "+token, 30* 24 * 60 * 60);
					return BackResult.build("200","修改密码成功");
				}else{
					return BackResult.build("400","修改密码失败，旧密码错误");
				}
			}
		} else {
			return BackResult.build("400","信息填写不完整");
		}
	}
	public BackResult register(User user, String validateCode,String officeName,
			HttpServletRequest request) {
		String userType = user.getUserType();
		List<String> messages = Lists.newArrayList(); // 消息
		//从redis获取指定验证码
		List<String> validateCodeMsg = new ArrayList<String>();
		String mobileFromRedisCode = jedisClient.get("registercode: "+user.getMobile());
		if (StringUtil.isEmpty(mobileFromRedisCode)) {
			return BackResult.build("400","短信验证码超时");
		}
		if (!mobileFromRedisCode.equals(validateCode)) {
			return BackResult.build("400","短信验证码错误");
		}
		if(!validateCodeMsg.isEmpty()) { // 验证码校验不通过
			messages.addAll(validateCodeMsg);
			return BackResult.build("400",messages.get(0));
		} else {
			// 默认个人用户
			Office company = new Office();
			company.setId(Global.getConfig("front.companyid"));//0
			Office office = new Office();
			office.setId(Global.getConfig("front.officeid"));// "-"
			user.setCompany(company);
			user.setOffice(office);
			user.setLoginName(user.getMobile());
			if(ValidateTool.isEmptyOrNull(user.getMobile()) || !ValidateTool.isMobile(user.getMobile())) {
				return BackResult.build("500", "手机号非法");
			}
			if(ValidateTool.isEmptyOrNull(user.getName())) {
				user.setName(user.getMobile());
			}
			if("1".equals(userType) && ValidateTool.isEmptyOrNull(officeName)) {
				return BackResult.build("500", "请填写企业名称");
			}
			user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
			User exuser = ckeckTelephoneService.getUserByTelephone(user.getMobile());
			if (exuser != null) {  //手机号已注册
				return BackResult.build("400","手机号已注册");
			} 
			String password1 = request.getParameter("newPassword");
			String password2 = request.getParameter("confirmNewPassword");
			if(password1==null||password2==null){
				return BackResult.build("400","密码不一致");
			}
			if (!password1.equals(password2) || StringUtils.isEmpty(password1) || StringUtils.isEmpty(password2)) {
				return BackResult.build("400","密码不一致");
			}
			String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
			if (!password1.matches(regex)||!password2.matches(regex)) {
				return BackResult.build("400","密码为6-16位数字和字母的组合");
			}
		}
		if(messages.isEmpty()) {
			// 角色数据有效性验证，过滤不在授权内的角色
			List<Role> roleList = Lists.newArrayList();
			Role r = new Role();
			r.setId(Global.getConfig("front.roleid"));//2
			// 如果是企业注册
			if("1".equals(userType)) {
				r.setId(Global.getConfig("front.e.roleid"));
				// 新建普通单位
				Office office = new Office();
				String cid = UUID.randomUUID().toString().replace("-", "");
				office.setId(cid);
				Office parent = new Office();
				parent.setId(Global.getConfig("front.e.companyid"));
				office.setParent(parent);
				office.setParentIds("0,1,"+parent.getId()+",");
				office.setName(officeName);
				Area area = new Area();
				area.setId("20"); // 区域默认跟平台保持一致
				office.setArea(area);
				office.setType("2");
				office.setUseable("1"); // 可登陆
				office.setDelFlag("0"); // 未删除
				office.setFlatType("5");
				Date date = new Date();
				office.setCreateDate(date);
				office.setUpdateDate(date);
				User admin = new User(); // 操作用户默认都是管理员
				admin.setId("1");
				office.setCreateBy(admin);
				office.setUpdateBy(admin);
				officeService.savef(office); // 保存客运公司
				user.setCompany(office);
				user.setOffice(office);
		}
			roleList.add(r);
			user.setRoleList(roleList);
			systemService.savePubUser(user);
			//注册统计
			String device=request.getParameter("device");
			CountInfo countInfo=tCountService.findList(null).get(0);
			if(device!=null&&device.equals("android")){
				int t=countInfo.getAndriodNum()+1;
				countInfo.setAndriodNum(t);
			}else{
				int t=countInfo.getIosNum()+1;
				countInfo.setIosNum(t);
			}
			countInfo.setTotalCount(countInfo.getAndriodNum()+countInfo.getIosNum()+countInfo.getHtmlNum());
			tCountService.update(countInfo);
			return BackResult.ok(true);
		} else {
			return BackResult.build("400",messages.get(0));
		}
	}
	public BackResult getSiteList(String spottypes) {
		TSitedtl query = new TSitedtl();
		if(!ValidateTool.isEmptyOrNull(spottypes)) {
			query.setSpottypes(spottypes.split(","));
		}
		List<TSitedtl> siteList = sitedtlService.findList(query);
		// 对每个数据集进行格式化
		String[] characters = new String[]{"热门","A","B","C","D","F","G","H","J","K","L","M","N","P","Q","R","S","T","W","X","Y","Z"};
		List<Map<String,Object>> data = Lists.newArrayList();
		for(int i=0;i<characters.length;i++) {
			Map<String,Object> group = Maps.newHashMap();
			List<TSitedtl> list = Lists.newArrayList();
			group.put("character", characters[i]);
			group.put("list", list);
			for(TSitedtl site : siteList) {
				String c = site.getQuerycode().substring(0, 1);
				if(c.toUpperCase().equals(characters[i]) ||
						(characters[i]=="热门" && "1".equals(site.getIshot()))) {
					@SuppressWarnings("unchecked")
					List<TSitedtl> temp = (List<TSitedtl>) group.get("list");
					String queryCode = site.getQuerycode().replace(" ", "_");
					queryCode = StringUtil.toCapitalizeCamelCase(queryCode);
					site.setQuerycode(queryCode);
					temp.add(site);
				}
			}
			data.add(i, group);
		}
		return BackResult.ok(data);
	}
	public BackResult modifyNickName(String token,HttpServletRequest request) {
			User opt = userService.get(request.getParameter("userid"));
			if(opt != null){
				opt.setName(request.getParameter("nickname"));//昵称
				// 更新用户数据
				userDao.update(opt);
				//更改token信息
				opt.setPassword(null);
				opt.setUid(opt.getId());
				if ("wx".equals(request.getParameter("type"))) {//微信提交,不需要token
					return BackResult.build("200", "个人信息修改成功");
				}
				jedisClient.set(MobileJsonController.FRONT_USER+" : "+token, JsonUtils.objectToJson(opt));
				return BackResult.build("200", "个人信息修改成功");
			}
			return BackResult.build("400", "个人信息修改失败");
	}
	/**
	 * 根据定位城市名获取id
	 */
	public BackResult getSiteidByName(String cityname) {
		TSitedtl site = new TSitedtl();
		site.setSitename(cityname.trim());
		List<TSitedtl> list = tSitedtlService.findList(site);
		if(list==null || list.isEmpty()) {
			return BackResult.build("400", "未查询到id");
		} else {
			return BackResult.ok(list.get(0));
		}
	}
	
	public BackResult modifyUserImage(HttpServletRequest request, HttpServletResponse response,
			String userid,String token) throws Exception {
		User user = userService.get(userid);
		if (user==null) {
			return BackResult.build("400", "查询用户信息失败");
		}
		String message = "";
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        //文件保存目录路径
        String savePath = "C:\\images\\userfiles\\userimage\\";
        //检查目录
        File uploadDir = new File(savePath);
        //如果不存在，创建文件夹
        if (!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        //此处是直接采用Spring的上传
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mf = entity.getValue();
            String fileFullname = mf.getOriginalFilename();
            //检查扩展名
            String fileExt = fileFullname.substring(fileFullname.lastIndexOf(".") + 1).toLowerCase();
            String newFileName = userid + "." + fileExt;
            File uploadFile = new File(savePath + newFileName);
            try {
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                message = "文件上传成功";
                //数据库保存上传路径
                String saveUserImagePath = "/userfiles/userimage/"+newFileName;
                userService.updateDataPath(saveUserImagePath, userid);
    			user.setPassword(null);
    			user.setUserimage(saveUserImagePath);
    			user.setUid(user.getId());//手机端返回id关键字,uid替代
    			//把用户信息存到jedis,key就是token,value就是用户信息
    			jedisClient.set(MobileJsonController.FRONT_USER+" : "+token, JsonUtils.objectToJson(user));
            } catch (IOException e) {
            	message = "文件上传失败";
            }
        }
		return BackResult.build("200", message);
	}
	public BackResult mobileQqcallBack(String openid) {
		String loginName = userService.getLoginNameByQqOpenid(openid);
		if (StringUtils.isEmpty(loginName)) {
			// 未绑定。 跳转到绑定页面，要求用户输入账户密码
			return BackResult.build("400", "用户未绑定帐号");
		} else {
			// 已绑定。直接跳转登录成功页面
			//生成token
			String token = UUIDUtils.getId();
			User user = userService.getUserByLoginName(loginName);
			user.setPassword(null);
			user.setUid(user.getId());//手机端返回id关键字,uid替代
			//把用户信息存到jedis,key就是token,value就是用户信息
			jedisClient.set(MobileJsonController.FRONT_USER+" : "+token, JsonUtils.objectToJson(user));
			return BackResult.ok(token);
		}
	}
	public BackResult mobileBindQq(HttpServletRequest request,String validateCode) throws Exception {
		String loginName =request.getParameter("loginName");
		String openid =request.getParameter("openid");
		String password1 = request.getParameter("newPassword");
        String password =request.getParameter("confirmNewPassword");
		String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
		if (StringUtils.isNotEmpty(password1)&&StringUtils.isNotEmpty(password)) {
			if (!password1.matches(regex)||!password.matches(regex)||!password1.equals(password)) {
				return BackResult.build("400","密码为6-16位数字和字母的组合");
			}
		}
        String mobileFromRedisCode = jedisClient.get("registercode: "+loginName);
        if (StringUtil.isEmpty(mobileFromRedisCode)) {
			return BackResult.build("400","短信验证码超时");
		}
		if (!mobileFromRedisCode.equals(validateCode)) {
			return BackResult.build("400","短信验证码错误");
		}
		if(StringUtils.isEmpty(loginName)||StringUtils.isEmpty(openid)) { 
			return BackResult.build("400","参数错误");
		}
		//数据库中已经有loginname
		User user = userService.getUserByLoginName(loginName);
		if (user!=null) {
			userService.updateUserByOPenID(openid,loginName);
			//生成token
			String token = UUIDUtils.getId();
			user.setPassword(null);
			user.setUid(user.getId());//手机端返回id关键字,uid替代
			//把用户信息存到jedis,key就是token,value就是用户信息
			jedisClient.set(MobileJsonController.FRONT_USER+" : "+token, JsonUtils.objectToJson(user));
			return BackResult.ok(token);
		}else{
			//没有loginname,需要注册
			User qqUser = new User();
			Office company = new Office();
			company.setId(Global.getConfig("front.companyid"));//0
			Office office = new Office();
			office.setId(Global.getConfig("front.officeid"));// "-"
			qqUser.setCompany(company);
			qqUser.setOffice(office);
			qqUser.setLoginName(loginName);
			qqUser.setName(loginName);
			qqUser.setPassword(SystemService.entryptPassword(password));
			List<Role> roleList = Lists.newArrayList();
			Role r = new Role();
			r.setId(Global.getConfig("front.roleid"));//2
			roleList.add(r);
			qqUser.setRoleList(roleList);
			systemService.savePubUser(qqUser);
			userService.updateUserByOPenID(openid,loginName);
			String token = UUIDUtils.getId();
			qqUser.setPassword(null);
			qqUser.setUid(qqUser.getId());//手机端返回id关键字,uid替代
			//把用户信息存到jedis,key就是token,value就是用户信息
			jedisClient.set(MobileJsonController.FRONT_USER+" : "+token, JsonUtils.objectToJson(qqUser));
			return BackResult.ok(token);
		}
	}
	public BackResult mobileWxcallBack(String unionid) throws IOException, ServletException {
	        String loginName = userService.getLoginName(unionid);
			if (StringUtils.isEmpty(loginName)){
				//未绑定。 跳转到绑定页面，要求用户输入账户密码
				return BackResult.build("400", "用户未绑定帐号");
			} else {
				//已绑定
				//生成token
				String token = UUIDUtils.getId();
				User user = userService.getUserByLoginName(loginName);
				user.setPassword(null);
				user.setUid(user.getId());//手机端返回id关键字,uid替代
				//把用户信息存到jedis,key就是token,value就是用户信息
				jedisClient.set(MobileJsonController.FRONT_USER+" : "+token, JsonUtils.objectToJson(user));
				return BackResult.ok(token);
			}
	}
	public BackResult mobileBindWx(HttpServletRequest request,String validateCode) throws Exception {
		String loginName =request.getParameter("loginName");
        String unionid =request.getParameter("unionid");
        String password1 = request.getParameter("newPassword");
        String password =request.getParameter("confirmNewPassword");
		String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
		if (StringUtils.isNotEmpty(password1)&&StringUtils.isNotEmpty(password)) {
			if (!password1.matches(regex)||!password.matches(regex)||!password1.equals(password)) {
				return BackResult.build("400","密码为6-16位数字和字母的组合");
			}
		}
        String mobileFromRedisCode = jedisClient.get("registercode: "+loginName);
		if (StringUtil.isEmpty(mobileFromRedisCode)) {
			return BackResult.build("400","短信验证码超时");
		}
		if (!mobileFromRedisCode.equals(validateCode)) {
			return BackResult.build("400","短信验证码错误");
		}
		if(StringUtils.isEmpty(loginName)||StringUtils.isEmpty(unionid)) { 
			return BackResult.build("400","参数错误");
		}
      	//数据库中已经有loginname
        User user = userService.getUserByLoginName(loginName);
        if (user!=null) {
        	userService.updateUserByUnionID(unionid,loginName);
        	//生成token
			String token = UUIDUtils.getId();
			user.setPassword(null);
			user.setUid(user.getId());//手机端返回id关键字,uid替代
			//把用户信息存到jedis,key就是token,value就是用户信息
			jedisClient.set(MobileJsonController.FRONT_USER+" : "+token, JsonUtils.objectToJson(user));
			return BackResult.ok(token);
		}else{
			//没有loginname,需要注册
			User wxUser = new User();
			Office company = new Office();
			company.setId(Global.getConfig("front.companyid"));//0
			Office office = new Office();
			office.setId(Global.getConfig("front.officeid"));// "-"
			wxUser.setCompany(company);
			wxUser.setOffice(office);
			wxUser.setLoginName(loginName);
			wxUser.setName(loginName);
			wxUser.setPassword(SystemService.entryptPassword(password));
			List<Role> roleList = Lists.newArrayList();
			Role r = new Role();
			r.setId(Global.getConfig("front.roleid"));//2
			roleList.add(r);
			wxUser.setRoleList(roleList);
			systemService.savePubUser(wxUser);
			userService.updateUserByUnionID(unionid,loginName);
			String token = UUIDUtils.getId();
			wxUser.setPassword(null);
			wxUser.setUid(wxUser.getId());//手机端返回id关键字,uid替代
			//把用户信息存到jedis,key就是token,value就是用户信息
			jedisClient.set(MobileJsonController.FRONT_USER+" : "+token, JsonUtils.objectToJson(wxUser));
			return BackResult.ok(token);
		}
	}

	public BackResult getUserInfoById(String userid) {
		User user = userService.get(userid);
		if (user==null) {
			return BackResult.build("400", "未查询到用户信息");
		}
		return BackResult.ok(user);
	}

	public void readText(HttpServletResponse response) throws Exception {
		// 设置浏览器打开文件时采用的编码。
		response.setHeader("Content-Type","text/html;charset=UTF-8");
		String filePath = "C:\\images\\userfiles\\update.txt";
		File file = new File(filePath);
		if(file.isFile() && file.exists()) {      
			InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");   
			BufferedReader br = new BufferedReader(isr);     
			String lineTxt = null;      
			while ((lineTxt = br.readLine()) != null) {    
				response.getWriter().println(lineTxt); 
			}     
			br.close();    
		}  
	}
}
